package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.constants.message.UpdateArticleMess;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    CacheService cacheService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 保存阅读行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.检查参数
        if(dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.okResult();
        }

        if (dto.getCount() == 0) {
            dto.setCount(1);
        }

        // 4 更新次数
        String objStr = (String) cacheService.hGet(UserRelationConstants.BEHAVIOR_READ + user.getId(),
                dto.getArticleId().toString());
        if (StringUtils.isNotBlank(objStr)) {
            ReadBehaviorDto behaviorDto = JSON.parseObject(objStr, ReadBehaviorDto.class);
            dto.setCount( behaviorDto.getCount() + 1 );
        }


        // 3 记录阅读行为
        cacheService.hPut(UserRelationConstants.BEHAVIOR_READ + user.getId(),
                dto.getArticleId().toString(), JSON.toJSONString(dto));

        //**********实时计算消息**********************
        UpdateArticleMess mess =
                new UpdateArticleMess(UpdateArticleMess.UpdateArticleType.VIEWS, dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));
        log.info("VIEWS:{}", mess);
        //******************************************


        // 4 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
